package cn.handy.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hanshuai
 * @Description: {zuul拦截器}
 * @date 2019/3/28 11:33
 */
@Component
public class TokenFilter extends ZuulFilter {
    @Value("${memberSwaggerLocation}")
    private String memberSwaggerLocation;
    @Value("${orderSwaggerLocation}")
    private String orderSwaggerLocation;
    /**
     * 拦截类型-pre请求前拦截
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 拦截级别,多个拦截器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启拦截
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 拦截方法
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String servletPath = request.getServletPath();
        // 判断是否为swagger请求,是的话不拦截
        if (memberSwaggerLocation.equals(servletPath) || orderSwaggerLocation.equals(servletPath)){
            return null;
        }
        String userToken = request.getParameter("userToken");
        // 如果为空
        if (StringUtils.isEmpty(userToken)){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            currentContext.setResponseBody("userToken is null");
            return null;
        }
        // 不为空正常执行
        return null;
    }
}
